import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:smart_ai_dart/pages/search_page/controller.dart'
    as search_controller;

class SearchPage extends GetView<search_controller.SearchController> {
  const SearchPage({super.key});

  @override
  Widget build(BuildContext context) {
    Get.put(search_controller.SearchController());

    return Scaffold(
      appBar: _buildSearchBar(),
      body: Obx(() {
        if (controller.searchTextController.text.isEmpty) {
          return _buildSearchContent();
        } else if (controller.searchResults.isEmpty) {
          return Center(child: Text('search_no_results'.tr));
        } else {
          return ListView.builder(
            itemCount: controller.searchResults.length,
            itemBuilder: (context, index) {
              final item = controller.searchResults[index];
              return ListTile(
                title: Text(item),
              );
            },
          );
        }
      }),
    );
  }

  AppBar _buildSearchBar() {
    return AppBar(
      title: Container(
        height: 36, // 设置输入框的高度
        alignment: Alignment.center, // 让内容垂直居中
        decoration: BoxDecoration(
          color: Colors.white, // 添加白色背景
          borderRadius: BorderRadius.circular(8), // 可选：圆角
        ),
        child: Obx(
          () {
            return TextField(
              textAlignVertical: TextAlignVertical.center,
              inputFormatters: [LengthLimitingTextInputFormatter(20)],
              decoration: InputDecoration(
                border: InputBorder.none,
                isDense: true,
                hintText: 'search_hint'.tr,
                hintStyle: TextStyle(color: Colors.black.withOpacity(0.7)),
                suffixIcon: controller.searchText.isEmpty
                    ? null
                    : IconButton(
                        icon: const Icon(Icons.clear, color: Colors.black),
                        onPressed: () {
                          controller.searchTextController.clear();
                        },
                      ),
                contentPadding:
                    const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
              ),
              style: const TextStyle(color: Colors.black),
              onChanged: (value) {
                // 直接更新响应式变量
                controller.searchText.value = value;
              },
              onSubmitted: (_) => controller.search(),
              controller: controller.searchTextController,
            );
          },
        ),
      ),
      actions: [
        IconButton(
          icon: const Icon(
            Icons.search,
            color: Colors.white,
          ),
          onPressed: controller.search,
        ),
      ],
    );
  }

  Widget _buildSearchContent() {
    return SingleChildScrollView(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildSearchHistory(),
          _buildHotSearches(),
        ],
      ),
    );
  }

  Widget _buildSearchHistory() {
    return controller.searchHistory.isNotEmpty
        ? Column(
            children: [
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 12.0),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      'search_history'.tr,
                      style: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                    IconButton(
                      icon: const Icon(Icons.delete_outline),
                      onPressed: controller.clearSearchHistory,
                    ),
                  ],
                ),
              ),
              Padding(
                padding: const EdgeInsets.symmetric(horizontal: 12.0),
                child: Align(
                  alignment: Alignment.centerLeft,
                  child: Wrap(
                    spacing: 8,
                    runSpacing: 4,
                    children: controller.searchHistory
                        .take(8)
                        .map((item) => GestureDetector(
                              onTap: () {
                                controller.searchTextController.text = item;
                                controller.search();
                              },
                              child: Chip(
                                label: Text(item),
                              ),
                            ))
                        .toList(),
                  ),
                ),
              ),
            ],
          )
        : const SizedBox.shrink();
  }

  Widget _buildHotSearches() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: const EdgeInsets.all(12.0),
          child: Text(
            'hot_searches'.tr,
            style: const TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
        GridView.builder(
          physics: const NeverScrollableScrollPhysics(),
          shrinkWrap: true,
          gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2,
            childAspectRatio: 5,
            crossAxisSpacing: 10,
            mainAxisSpacing: 0,
          ),
          padding: const EdgeInsets.symmetric(horizontal: 16),
          itemCount: controller.hotSearches.take(12).length,
          itemBuilder: (context, index) {
            final item = controller.hotSearches[index];
            return GestureDetector(
              onTap: () {
                controller.searchTextController.text = item;
                controller.search();
              },
              child: Row(
                children: [
                  Container(
                    width: 8,
                    height: 8,
                    decoration: const BoxDecoration(
                      color: Colors.blue,
                      shape: BoxShape.circle,
                    ),
                  ),
                  const SizedBox(width: 8),
                  Text(item),
                ],
              ),
            );
          },
        ),
      ],
    );
  }
}
